package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.entity.adminlogsInfo;
import com.example.computer_exam_training_sys.service.admin_logsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/adminLogs")
@CrossOrigin
public class adminlogsController {

    @Autowired
    private admin_logsService service;

    // 遍历查询所有日志（无条件）
    @GetMapping("/all")
    public List<adminlogsInfo> findAllLogs() {
        return service.findAll(null, null);
    }

    // 条件查询：根据管理员ID或操作类型
    @GetMapping("/search")
    public List<adminlogsInfo> searchLogs(
            @RequestParam(value = "adminId", required = false) Integer adminId,
            @RequestParam(value = "operationType", required = false) String operationType) {
        return service.findAll(adminId, operationType);
    }

    // 新增日志
    @PostMapping("/add")
    public int addLog(@RequestBody adminlogsInfo log) {
        return service.addLog(log);
    }

    // 获取所有操作类型
    @GetMapping("/operationTypes")
    public List<String> getOperationTypes() {
        return service.getOperationTypes();
    }

    // 导出日志
    @GetMapping("/export")
    public void exportLogs(
            @RequestParam(value = "adminId", required = false) Integer adminId,
            @RequestParam(value = "operationType", required = false) String operationType,
            HttpServletResponse response) throws IOException {
        List<adminlogsInfo> logs = service.findAll(adminId, operationType);
        String csv = service.generateCsv(logs);
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=admin_logs.csv");
        response.getWriter().write(csv);
    }

    // 删除日志
    @DeleteMapping("/delete/{logId}")
    public int deleteLog(@PathVariable Integer logId) {
        return service.deleteLog(logId);
    }
}